package com.peng.rpc.netty.server;

import com.peng.rpc.common.server.AbstractRpcServer;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import com.peng.rpc.provider.DefaultServiceProvider;
import com.peng.rpc.registry.NacosServiceRegistry;
import com.peng.rpc.registry.ShutDownHook;
import com.peng.rpc.serializer.CommonSerializer;
import com.peng.rpc.netty.util.CommonDecoder;
import com.peng.rpc.netty.util.CommonEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/3/1 20:00
 */
@Slf4j
public class NettyRpcServer extends AbstractRpcServer {

    private CommonSerializer serializer;

    public NettyRpcServer(String host, int port) {
        this(DEFAULT_SERIALIZER, host, port);
    }
    public NettyRpcServer(int serializerCode, String host, int port) {
        this.serializer = CommonSerializer.getSerializerByCode(serializerCode);
        this.host = host;
        this.port = port;
        this.serviceProvider = new DefaultServiceProvider();
        this.serviceRegistry = new NacosServiceRegistry();
        servicesScan();
    }

    @Override
    public void start() {
        if (serializer == null) {
            log.error("未设置序列化器，无法发送请求");
            throw new RpcException(RpcError.SERIALIZER_UNSETTED);
        }
        ShutDownHook.addShutDownHooks();
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG, 256)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new CommonEncoder(serializer));
                            pipeline.addLast(new CommonDecoder());
//                            pipeline.addLast(new IdleStateHandler(30, 0,0, TimeUnit.SECONDS));
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(host, port).sync();
            ShutDownHook.addShutDownHooks();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("服务器处理过程中出现异常：{}", e.getMessage());
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void publishServices(List services, List<Class> serviceClasses) {
        if (serializer == null) {
            throw new RpcException(RpcError.SERIALIZER_UNSETTED);
        }
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        for (int i = 0; i < services.size(); i++) {
            serviceProvider.addService(services.get(i), serviceClasses.get(i).getCanonicalName());
            serviceRegistry.register(serviceClasses.get(i).getCanonicalName(), inetSocketAddress);
        }
        start();
    }
}
